package com.ttbj.task;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.ttbj.constant.DispatchEnum;
import com.ttbj.order.component.OrderCacheComponent;
import com.ttbj.product.api.OrderFacade;
import com.ttbj.product.api.WaybillFacade;
import com.ttbj.product.bean.dto.OrderDto;
import com.ttbj.product.bean.exception.BusinessException;
import com.ttbj.util.Assert;

/**
 * 司机订单任务调度器
 * 
 * @author Administrator
 *
 */
public class WaybillTask {
	private static final Logger logger = LoggerFactory.getLogger(WaybillTask.class);

	@Autowired
	private OrderFacade orderFacade = null;

	@Autowired
	private OrderCacheComponent orderCacheComponent = null;

	@Autowired
	private WaybillFacade waybillFacade = null;

	/**
	 * 持续生成
	 */
	public void redeploy() {
		logger.info("---定时派单开始----");
		try {
			Long orderId = orderCacheComponent.get();
			if (null == orderId) {
				logger.info("未获取到订单，返回");
				return;
			}
			OrderDto orderDto = orderDto(orderId);
			if(!assertion(orderDto.getOrderDriverRequire(), orderDto.getOrderDriverAlready())){
				return;
			}
			waybillFacade.newWaybill(orderDto);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private boolean filterHand(Integer flag) {
		Boolean isHand = null;
		switch (flag) {
		case 1:
			isHand = DispatchEnum.AUTO.isHand;
		case 0:
			isHand = DispatchEnum.HAND.isHand;
			break;
		default:
			isHand = DispatchEnum.AUTO.isHand;
			break;
		}
		logger.info("是否是自动派单:{}",isHand);
		return isHand;
	}

	/**
	 * 设置
	 * 
	 * @param orderId
	 * @return
	 * @throws Exception
	 */
	private OrderDto orderDto(Long orderId) throws Exception {
		if (null == orderId) {
			return null;
		}
		return orderFacade.complexDetailOrder(orderId);
	}

	private Boolean assertion(Integer orderDriverRequire, Integer orderDriverAlready) throws BusinessException {
		if(null == orderDriverAlready){
			throw new BusinessException("已有车辆不能出现空值", 9999);
		}
		if (orderDriverRequire <= orderDriverAlready) {
			return false;
		}
		if (null == orderDriverRequire || 0 >= orderDriverRequire) {
			throw new BusinessException("需求车辆不能少于1辆", 9999);
		}
		return true;
	}

}
